package co.fitstart.weapp.api.web.controller.course;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.DateUtils;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.user.Student;
import co.fitstart.entity.user.User;
import co.fitstart.entity.user.bwh.BwhRecord;
import co.fitstart.weapp.api.service.BwhRecordService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.UserService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/profile/courses/{courseId}/bwh-records")
public class CourseBwhController {

    private static final Logger logger = LoggerFactory.getLogger(CourseBwhController.class);

    @Autowired
    private UserService userService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private BwhRecordService bwhRecordService;

    /**
     * 
     * @param unionid
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult list(@RequestParam("unionid") String unionid,
                           @PathVariable("courseId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            List<BwhRecord> bwhRecords = bwhRecordService.list(courseRound);
            
            boolean couldRecord = false;
            if(courseRound.getCourseType().isOnline() && (bwhRecords.isEmpty() || !DateUtils.isSameWeek(bwhRecords.get(bwhRecords.size() - 1).getCreateTime(), new Date()))) {
                couldRecord = true;
            }
            
            httpResult.success().message("获取数据成功")
                                .data("courseType", courseRound.getCourseType())
                                .data("bwhRecords", bwhRecords)
                                .data("couldRecord", couldRecord);
        } catch (BusinessException e) {
            httpResult.fail("1").message(e.getMessage());
        } catch (Exception e) {
            logger.error("listCourseRoundBwh() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 线上课程每周可记录一次三围数据（胸围、腰围、臀围、体重）
     * @param unionid
     * @param courseRoundId
     * @param bwhRecord
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "unionid")
    public HttpResult create(@RequestParam("unionid") String unionid,
                             @PathVariable("courseId") Long courseRoundId,
                             @RequestBody BwhRecord bwhRecord) {
        HttpResult httpResult = new HttpResult();
        
        try {
            User user = userService.load(unionid);
            Student student = userService.getStudent(user);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            
            courseRoundService.validate(student, courseRound);
            
            bwhRecordService.create(courseRound, bwhRecord);
            
            httpResult.success().message("记录三围数据成功");
        } catch (BusinessException e) {
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            logger.error("listCourseRoundBwh() error", e);
            httpResult.fail("500").message("记录三围数据失败");
        }
        
        return httpResult;
    }
}
